C#对称加密(3des)和非对称加密(rsa)算法
3DES加密/解密算法的C#实现:(实现的方式很多,仅供参考)
public static bool DecryptFromBase64(string base64String, string key,out string DecryptString) { DecryptString = ""; try { // encode to bytes byte[] KEY = HexStringToByteArray(key); byte[] CRYPTSTRING = Convert.FromBase64String(base64String); //set iv and key byte[] tmpiv = { 49, 50, 51, 52, 53, 54, 55, 56 }; byte[] tmpkey = { 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7 }; for (int ii = 0; ii < 24; ii++) { tmpkey[ii] = KEY[ii]; } TripleDESCryptoServiceProvider dsp = new TripleDESCryptoServiceProvider(); dsp.Mode = System.Security.Cryptography.CipherMode.CBC; dsp.Padding = System.Security.Cryptography.PaddingMode.PKCS7; ICryptoTransform tridesencrypt = dsp.CreateDecryptor(tmpkey, tmpiv); using (var ms = new MemoryStream(CRYPTSTRING)) { using (var cs = new CryptoStream(ms, tridesencrypt, CryptoStreamMode.Read)) { var sr = new StreamReader(cs, Encoding.UTF8); // 2015/11/11 修改 读取全部内容,而不是只读第一行,此问题乃是算法的bug DecryptString = sr.ReadToEnd();// sr.ReadLine(); } } dsp.Clear(); return true; } catch (Exception e) { return false; } } public static bool Crypt3DESToBase64(string CryptString, string Key, out string DecryptString) { DecryptString = ""; try { // encode to bytes byte[] KEY = HexStringToByteArray(Key); byte[] CRYPTSTRING = System.Text.Encoding.UTF8.GetBytes(CryptString); //set iv and key byte[] tmpiv = { 49, 50, 51, 52, 53, 54, 55, 56 }; byte[] tmpkey = { 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7 }; for (int ii = 0; ii < 24; ii++) { tmpkey[ii] = KEY[ii]; } TripleDESCryptoServiceProvider dsp = new TripleDESCryptoServiceProvider(); dsp.Mode = System.Security.Cryptography.CipherMode.CBC; dsp.Padding = System.Security.Cryptography.PaddingMode.PKCS7; ICryptoTransform tridesencrypt = dsp.CreateEncryptor(tmpkey, tmpiv); byte[] results = tridesencrypt.TransformFinalBlock(CRYPTSTRING, 0, CRYPTSTRING.Length); DecryptString = Convert.ToBase64String(results); dsp.Clear(); return true; } catch (Exception e) { return false; } } public static byte[] HexStringToByteArray(string s) { Byte[] buf = new byte[s.Length / 2]; for (int i = 0; i < buf.Length; i++) { buf[i] = (byte)(chr2hex(s.Substring(i * 2, 1)) * 0x10 + chr2hex(s.Substring(i * 2 + 1, 1))); } return buf; } private static byte chr2hex(string chr) { switch (chr) { case "0": return 0x00; case "1": return 0x01; case "2": return 0x02; case "3": return 0x03; case "4": return 0x04; case "5": return 0x05; case "6": return 0x06; case "7": return 0x07; case "8": return 0x08; case "9": return 0x09; case "A": return 0x0a; case "B": return 0x0b; case "C": return 0x0c; case "D": return 0x0d; case "E": return 0x0e; case "F": return 0x0f; } return 0x00; }
在以上算法中,key为一个48位的字符串,别的就没特别要注意的了。
RSA加密算法(根据MSDN文档实现):
/// <summary> /// 使用rsa非对称加密算法加密文本内容 /// </summary> /// <param name="contentBytes">待加密内容byte数组</param> /// <param name="publicKey">公开密钥</param> /// <param name="DoOAEPPadding">建议为false</param> /// <returns>加密后的byte[]</returns> public static byte[] RSAEncryptContent(byte[]contentBytes,RSAParameters publicKey,bool DoOAEPPadding) { try { byte[] encryptedData; using (RSACryptoServiceProvider provider = new RSACryptoServiceProvider()) { provider.ImportParameters(publicKey); encryptedData = provider.Encrypt(contentBytes, DoOAEPPadding); } return encryptedData; } catch (Exception e) { return null; } } /// <summary> /// 使用rsa非对称加密算法进行解密 /// </summary> /// <param name="cryptContentBytes">加密后的字节数组</param> /// <param name="privateKey">私有密钥</param> /// <param name="DoOAEPPadding">建议为false</param> /// <returns>解密后的内容数组</returns> public static byte[] RSADescryptContent(byte[]cryptContentBytes,RSAParameters privateKey,bool DoOAEPPadding) { try { byte[] decryptData; using (RSACryptoServiceProvider provider = new RSACryptoServiceProvider()) { provider.ImportParameters(privateKey); decryptData = provider.Decrypt(cryptContentBytes, DoOAEPPadding); } return decryptData; } catch (Exception e) { Console.WriteLine(e.Message); return null; } }
使用RSA加密/解密算法的方法:
//content为要进行加密的字符串
byte[] contentBytes = byteConverter.GetBytes(content); byte[] encryptBytes; byte[] decryptBytes; //待加密的字节数不能超过密钥的长度值除以 8 再减去 11(即:RSACryptoServiceProvider.KeySize / 8 - 11) int maxBlockSize; using(RSACryptoServiceProvider provider=new RSACryptoServiceProvider()) { maxBlockSize = provider.KeySize / 8 - 11; RSAParameters publicKey = provider.ExportParameters(false); // 小于最大块值,直接加密 if (contentBytes.Length <= maxBlockSize) { encryptBytes = EncryptContent(contentBytes, publicKey, false); } else { // 分块儿加密 using(MemoryStream plaintStream=new MemoryStream(contentBytes)) using(MemoryStream cryptStream=new MemoryStream()) { byte[] buffer = new byte[maxBlockSize]; int blockSize = plaintStream.Read(buffer, 0, maxBlockSize); while(blockSize>0) { byte[] encryptBlock = new byte[blockSize]; Array.Copy(buffer, encryptBlock, blockSize); byte[]encryptedBlock=EncryptContent(encryptBlock,publicKey,false); cryptStream.Write(encryptedBlock, 0, encryptedBlock.Length); blockSize = plaintStream.Read(buffer, 0, maxBlockSize); } encryptBytes = cryptStream.ToArray(); } } //加密后的字符串 string encryptString = byteConverter.GetString(encryptBytes); Console.WriteLine("加密结束"); Console.ReadLine(); Console.ReadLine();
// 以下为解密过程,解密过程也会有长度限制,可参考加密的方式进行解密 //string encryptString = byteConverter.GetString(encryptBytes); //RSAParameters privateKey = provider.ExportParameters(true); //decryptBytes = DecryptContent(encryptBytes, privateKey, false); //string decryptString = byteConverter.GetString(decryptBytes); //Console.WriteLine(decryptString); }